package com.ming.javaweb.filter;

import com.ming.javaweb.util.Constants;
import com.ming.javaweb.util.ExcludeResourceUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Tcm
 */
@WebFilter(filterName = "CharacterEncodingFilter",
        urlPatterns = {"/*"},
        initParams = {@WebInitParam(name = Constants.ENCODING,value = "UTF-8")}
)
public class CharacterEncodingFilter implements Filter {
    private String ENCODING = null;
    /**
     初始化filter时会回调
     */
    @Override
    public void init(FilterConfig filterConfig) {
        this.ENCODING = filterConfig.getInitParameter(Constants.ENCODING);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

        String requestURI = httpServletRequest.getRequestURI();
        System.out.println(requestURI);
        if (!ExcludeResourceUtil.shouldExclude(requestURI)) {
//            设置字符编码
            httpServletRequest.setCharacterEncoding(this.ENCODING);
            httpServletResponse.setCharacterEncoding(this.ENCODING);
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {

    }
}
